package com.ecommerce.service;

import com.ecommerce.entity.Address;
import com.ecommerce.repository.AddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class AddressService {

    @Autowired
    private AddressRepository addressRepository;

    // 获取用户的所有地址
    public Map<String, Object> getUserAddresses(Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Address> addresses = addressRepository.findByUserIdOrderByCreatedAtDesc(userId);
            response.put("success", true);
            response.put("addresses", addresses);
            response.put("message", "获取地址列表成功");
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取地址列表失败: " + e.getMessage());
            return response;
        }
    }

    // 获取用户的默认地址
    public Map<String, Object> getDefaultAddress(Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<Address> defaultAddress = addressRepository.findByUserIdAndIsDefaultTrue(userId);
            if (defaultAddress.isPresent()) {
                response.put("success", true);
                response.put("address", defaultAddress.get());
                response.put("message", "获取默认地址成功");
            } else {
                response.put("success", false);
                response.put("message", "未找到默认地址");
            }
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取默认地址失败: " + e.getMessage());
            return response;
        }
    }

    // 根据ID获取地址详情
    public Map<String, Object> getAddressById(Long userId, Long addressId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<Address> address = addressRepository.findByUserIdAndId(userId, addressId);
            if (address.isPresent()) {
                response.put("success", true);
                response.put("address", address.get());
                response.put("message", "获取地址详情成功");
            } else {
                response.put("success", false);
                response.put("message", "地址不存在");
            }
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取地址详情失败: " + e.getMessage());
            return response;
        }
    }

    // 创建新地址
    @Transactional
    public Map<String, Object> createAddress(Long userId, Address addressData) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 设置用户ID
            addressData.setUserId(userId);
            
            // 如果设置为默认地址，先清除其他默认地址
            if (Boolean.TRUE.equals(addressData.getIsDefault())) {
                addressRepository.clearDefaultAddress(userId);
            }
            
            // 保存地址
            Address savedAddress = addressRepository.save(addressData);
            
            response.put("success", true);
            response.put("address", savedAddress);
            response.put("message", "创建地址成功");
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "创建地址失败: " + e.getMessage());
            return response;
        }
    }

    // 更新地址
    @Transactional
    public Map<String, Object> updateAddress(Long userId, Long addressId, Address addressData) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<Address> existingAddress = addressRepository.findByUserIdAndId(userId, addressId);
            if (!existingAddress.isPresent()) {
                response.put("success", false);
                response.put("message", "地址不存在");
                return response;
            }
            
            Address address = existingAddress.get();
            
            // 更新字段
            address.setReceiverName(addressData.getReceiverName());
            address.setReceiverPhone(addressData.getReceiverPhone());
            address.setProvince(addressData.getProvince());
            address.setCity(addressData.getCity());
            address.setDistrict(addressData.getDistrict());
            address.setDetailAddress(addressData.getDetailAddress());
            address.setPostalCode(addressData.getPostalCode());
            address.setAddressTag(addressData.getAddressTag());
            
            // 如果设置为默认地址，先清除其他默认地址
            if (Boolean.TRUE.equals(addressData.getIsDefault())) {
                addressRepository.clearDefaultAddress(userId);
            }
            address.setIsDefault(addressData.getIsDefault());
            
            // 保存更新
            Address updatedAddress = addressRepository.save(address);
            
            response.put("success", true);
            response.put("address", updatedAddress);
            response.put("message", "更新地址成功");
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新地址失败: " + e.getMessage());
            return response;
        }
    }

    // 删除地址
    @Transactional
    public Map<String, Object> deleteAddress(Long userId, Long addressId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<Address> address = addressRepository.findByUserIdAndId(userId, addressId);
            if (!address.isPresent()) {
                response.put("success", false);
                response.put("message", "地址不存在");
                return response;
            }
            
            addressRepository.deleteById(addressId);
            
            response.put("success", true);
            response.put("message", "删除地址成功");
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除地址失败: " + e.getMessage());
            return response;
        }
    }

    // 设置默认地址
    @Transactional
    public Map<String, Object> setDefaultAddress(Long userId, Long addressId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<Address> address = addressRepository.findByUserIdAndId(userId, addressId);
            if (!address.isPresent()) {
                response.put("success", false);
                response.put("message", "地址不存在");
                return response;
            }
            
            // 清除其他默认地址
            addressRepository.clearDefaultAddress(userId);
            
            // 设置新的默认地址
            Address targetAddress = address.get();
            targetAddress.setIsDefault(true);
            addressRepository.save(targetAddress);
            
            response.put("success", true);
            response.put("message", "设置默认地址成功");
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "设置默认地址失败: " + e.getMessage());
            return response;
        }
    }
} 